<template>
  <div class="goodscates_params">
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 文字警告提示 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning" show-icon>
      </el-alert>
      <!-- 选择分类 -->
      <el-row class="select_cates">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 级联表 -->
          <el-cascader v-model="selectKeys" :options="catesList" :props="selectCatesProps" @change="selectCatesChange"></el-cascader>
        </el-col>
      </el-row>
      <!-- 标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="isDisabled" @click="addParamsDialogVisible = true">添加参数</el-button>
          <!-- 动态参数列表 -->
          <!-- TODO: 此处难道不应该显示那个直接挂数据吗 我理解的是应该一个表格复用
          显示哪个说明就是就是那个的数据 不用再判断many或者only -->
          <el-table border stripe :data="manyParamsList" style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag closable @close="tagClose(ind,scope.row)" class="tags" v-for="(item,ind) in scope.row.attr_vals" :key="ind">{{item}}</el-tag>
                <!-- 添加newtag -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#">
            </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作" width="300px">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="editParamsDialog(scope.row.attr_id)">编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="isDisabled" @click="addParamsDialogVisible = true">添加属性</el-button>
          <el-table border stripe :data="onlyParamsList" style="width: 100%">
            <el-table-column type="expand">
              <template>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#">
            </el-table-column>
            <el-table-column prop="attr_name" label="属性名称">
            </el-table-column>
            <el-table-column label="操作" width="300px">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="editParamsDialog(scope.row.attr_id)">编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog :title="'添加'+ title" :visible.sync="addParamsDialogVisible" @close="closeEvent" width="50%">
      <el-form :model="addParamsForm" :rules="addParamsFormrules" ref="addParamsFormRef" label-width="100px">
        <el-form-item :label="title" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog :title="'修改'+ title" :visible.sync="editParamsDialogVisible" @close="closeEditEvent" width="50%">
      <el-form :model="editParamsForm" :rules="editParamsFormrules" ref="editParamsFormRef" label-width="100px">
        <el-form-item :label="title" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'GoodsCatesPage',
  data () {
    return {
      // 分类列表
      catesList: [],
      // 选中分类ID数组
      selectKeys: [],
      // 级联表配置项
      selectCatesProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 默认选中
      activeName: 'many',
      // 参数列表数据源
      manyParamsList: [],
      // 属性列表数据源
      onlyParamsList: [],
      // 控制添加参数对话框
      addParamsDialogVisible: false,
      // 表单绑定数据对象
      addParamsForm: { attr_name: '' },
      // 添加参数表单验证规则
      addParamsFormrules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 控制编辑对话框
      editParamsDialogVisible: false,
      // 编辑表单数据对象
      editParamsForm: { attr_name: '' },
      // 编辑表单校验规则
      editParamsFormrules: { attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }] }
    }
  },
  computed: {
    // 控制按钮是否禁用
    isDisabled () {
      if (this.selectKeys.length !== 3) return true
      return false
    },
    // 获取请求数据的第三级id
    cateId () {
      if (this.selectKeys.length === 3) return this.selectKeys[this.selectKeys.length - 1]
      return null
    },
    // 动态获取标题
    title () {
      return this.activeName === 'many' ? '动态参数' : '静态属性'
    }
  },
  created () {
    this.getCatesList()
  },
  methods: {
    // 获取分类数据
    async getCatesList () {
      const { data: res } = await this.$http.get('categories', { params: { type: 3 } })
      if (res.meta.status !== 200) return this.message.error('操作失败，请重试！')
      // console.log(res)
      this.catesList = res.data
    },
    // 选中类别切换
    selectCatesChange () {
     if (this.selectKeys.length !== 3) {
      //  前面两项赋值空是为了避免中途切换到二级或一级类目 下面表格内容不变出现bug
       this.manyParamsList = []
       this.onlyParamsList = []
       this.selectKeys = []
       return false
     }
      this.getParamsData()
    },
    // 标签切换事件
    handleClick () {
      // console.log(this.activeName)
      this.getParamsData()
    },
    // 获取具体分类参数及属性
    async getParamsData () {
      // console.log(this.selectKeys)
      // 此处请求类别数据(根据类别和面板)
      // categories/:id/attributes
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: { sel: this.activeName }
      })
      if (res.meta.status !== 200) return this.$message.error('操作失败，请重试！')
      // console.log(res.data) 后期操作过后前面的数据会一起改
      res.data.forEach(element => {
        element.attr_vals = element.attr_vals ? element.attr_vals.split(',') : []
        element.inputVisible = false
        element.inputValue = ''
      })
      console.log(res.data)
      this.activeName === 'many' ? this.manyParamsList = res.data : this.onlyParamsList = res.data
    },
    // 添加参数
    addParams () {
      this.$refs.addParamsFormRef.validate(async valid => {
        // console.log(valid)
        // 发送请求
        if (!valid) return false
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error('操作失败，请重试！')
        // console.log(res.data)
        this.getParamsData()
        this.addParamsDialogVisible = false
      })
    },
    // 添加参数表单关闭
    closeEvent () {
      this.$refs.addParamsFormRef.resetFields()
    },
    // 编辑表单关闭
    closeEditEvent () {
      this.$refs.editParamsFormRef.resetFields()
    },
    async editParamsDialog (attrId) {
      // 获取数据
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${attrId}`, {
        params: { attr_sel: this.activeName }
      })
      if (res.meta.status !== 200) return this.$message.error('操作失败，请重试！')
      console.log(res)
      this.editParamsForm = res.data
      this.editParamsDialogVisible = true
    },
    // 编辑参数
    editParams () {
      this.$refs.editParamsFormRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`, {
          attr_name: this.editParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error('操作失败，请重试！')
        // console.log(res)
        this.getParamsData()
        this.editParamsDialogVisible = false
      })
    },
    // 删除参数
    async deleteParams (id) {
      const result = await this.$confirm('确认删除该参数?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)

      if (result !== 'confirm') return this.$message.info('已取消删除！')
      // 点击确认得到 confirm
      // 发送请求
      const { data: res } = await this.$http.delete(`categories/${this.cateId}d/attributes/${id}`)
      console.log(res)
      // 判断是否请求响应陈功
      if (res.meta.status !== 200) return this.$message('操作失败，请稍后重试！')
      // 重新加载列表
      this.getParamsData()
      // 提示操作成功
      this.$message.success('操作成功!')
    },
    // 添加新标签的切换输入框
    showInput (row) {
      row.inputVisible = true
      // $nextTick 用于控制执行顺序，他能够让内部代码在页面被重新渲染之后再执行
      this.$nextTick(_ => {
        // 自动获取光标
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 添加新标签
    handleInputConfirm (row) {
      if (row.inputValue.trim().length !== 0) {
        // 输入框不为空
        row.attr_vals.push(row.inputValue.trim())
        // 后台更新数据
        this.addTag(row)
      }
      // 为空直接到这里
      row.inputValue = ''
      row.inputVisible = false
    },
    // 添加标签
    async addTag (row) {
      // 后台数据更新
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(',')
      })
      if (res.meta.status !== 200) return this.$message.error('操作失败，请重试！')
      this.$message.success('操作成功！')
    },
    // 删除标签
    async tagClose (index, row) {
      row.attr_vals.splice(index, 1)
      this.addTag(row)
    }
  }
}
</script>

<style lang="less" scoped>
.select_cates {
  margin: 15px 0;
}
.tags,
.input-new-tag,
.button-new-tag {
  margin: 8px;
}
.input-new-tag {
  width: 120px;
}
</style>
